<?php

namespace app\admin\controller\groupon\store;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use app\admin\controller\groupon\Base;
use addons\groupon\library\traits\StoreTake;


/**
 * 自提点抽成
 *
 * @icon fa fa-circle-o
 */
class TakeLog extends Base
{
    use StoreTake;

    /**
     * Store模型对象
     * @var \app\admin\model\groupon\store\Store
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\groupon\store\TakeLog;
        $this->loadlang('groupon/order/order_item');
        $this->loadlang('groupon/order/order');
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


  /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            $nobuildfields = ['order_sn', 'goods_title', 'buyer_nickname', 'buyer_phone', 'user_nickname', 'user_phone','store_name'];
            list($where, $sort, $order, $offset, $limit) = $this->custombuildparams(null, $nobuildfields);

            $totalList = $this->buildSearchLog()
                ->where($where)
                ->order($sort, $order)
                ->select();

            $list = $this->buildSearchLog()
                ->where($where)
                ->with(['order', 'user', 'buyer', 'item', 'store'])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            // 处理顶部统计数据
            $total = count($totalList);
            $take_total = 0;
            $taked_total = 0;
            $delay_total = 0;
            $take_back_total = 0;
            foreach ($totalList as $key => $takeLog) {
                if ($takeLog['status'] == 1) {
                    $taked_total += $takeLog['take_money'];
                } else if ($takeLog['status'] == -1) {
                    $take_back_total += $takeLog['take_money'];
                } else if ($takeLog['status'] == 0) {
                    $delay_total += $takeLog['take_money'];
                }
                $take_total += $takeLog['take_money'];
            }

            $result = [
                "total" => $total,
                "rows" => $list,
                "take_total" => number_format($take_total, 2, '.', ''),
                "taked_total" => number_format($taked_total, 2, '.', ''),
                "delay_total" => number_format($delay_total, 2, '.', ''),
                "take_back_total" => number_format($take_back_total, 2, '.', '')
            ];

            return $this->success('操作成功', null, $result);
        }
        return $this->view->fetch();
    }



    /**
     * 抽成结算
     *
     * @param [type] $id
     * @return void
     */
    public function runMoney($id = null)
    {
        if (!$id) {
            $id = $this->request->get('id');
        }
        $row = $this->model->get($id);

        $result = \think\Db::transaction(function () use ($row) {
            return $this->runTakeMoney($row, 'admin');
        });

        if ($result) {
            $this->success('结算成功');
        } else {
            $this->error('订单已结算或没有要结算的抽成');
        }
    }


    /**
     * 抽成扣除
     *
     * @param [type] $id
     * @return void
     */
    public function backMoney($id = null)
    {
        if (!$id) {
            $id = $this->request->get('id');
        }
        $row = $this->model->get($id);

        $result = \think\Db::transaction(function () use ($row) {
            return $this->backTakeMoney($row, 'admin');
        });

        if ($result) {
            $this->success('退回成功');
        } else {
            $this->error('订单已退回或未结算');
        }
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if (!$ids) {
            $ids = $this->request->get('id');
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('row', $row);
        return $this->view->fetch();
    }


    // 构建查询条件
    private function buildSearchLog()
    {
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter = $filter ? $filter : [];

        $order_sn = isset($filter['order_sn']) ? $filter['order_sn'] : '';
        $goods_title = isset($filter['goods_title']) ? $filter['goods_title'] : '';
        $buyer_nickname = isset($filter['buyer_nickname']) ? $filter['buyer_nickname'] : '';
        $buyer_mobile = isset($filter['buyer_phone']) ? $filter['buyer_phone'] : '';
        $user_nickname = isset($filter['user_nickname']) ? $filter['user_nickname'] : '';
        $user_mobile = isset($filter['user_phone']) ? $filter['user_phone'] : '';
        $store_name = isset($filter['store_name']) ? $filter['store_name'] : '';

        $name = $this->model->getQuery()->getTable();
        $tableName = $name . '.';

        $takeLogs = $this->model;

        // 购买人
        if ($buyer_nickname || $buyer_mobile) {
            $takeLogs = $takeLogs->whereExists(function ($query) use ($buyer_nickname, $buyer_mobile, $tableName) {
                $userTableName = (new \app\admin\model\User())->getQuery()->getTable();

                $query = $query->table($userTableName)->where($userTableName . '.id=' . $tableName . 'buyer_id');

                if ($buyer_nickname) {
                    $query = $query->where('nickname', 'like', "%{$buyer_nickname}%");
                }

                if ($buyer_mobile) {
                    $query = $query->where('mobile', 'like', "%{$buyer_mobile}%");
                }

                return $query;
            });
        }

        // 自提点管理员
        if ($user_nickname || $user_mobile) {
            $takeLogs = $takeLogs->whereExists(function ($query) use ($user_nickname, $user_mobile, $tableName) {
                $userTableName = (new \app\admin\model\User())->getQuery()->getTable();

                $query = $query->table($userTableName)->where($userTableName . '.id=' . $tableName . 'user_id');

                if ($user_nickname) {
                    $query = $query->where('nickname', 'like', "%{$user_nickname}%");
                }

                if ($user_mobile) {
                    $query = $query->where('mobile', 'like', "%{$user_mobile}%");
                }

                return $query;
            });
        }

        // 自提点名称
        if ($store_name) {
            $takeLogs = $takeLogs->whereExists(function ($query) use ($store_name, $tableName) {
                $storeTableName = (new \app\admin\model\groupon\store\Store())->getQuery()->getTable();

                $query = $query->table($storeTableName)->where($storeTableName . '.id=' . $tableName . 'store_id');

                $query = $query->where('name', 'like', "%{$store_name}%");

                return $query;
            });
        }

        // 订单号
        if ($order_sn) {
            $takeLogs = $takeLogs->whereExists(function ($query) use ($order_sn, $tableName) {
                $orderTableName = (new \app\admin\model\groupon\order\Order())->getQuery()->getTable();

                $query = $query->table($orderTableName)->where($orderTableName . '.id=' . $tableName . 'store_id');

                $query = $query->where('order_sn', 'like', "%{$order_sn}%");

                return $query;
            });
        }

        // 快递方式 || 商品类型 (同一个表，写在一起)
        if ($goods_title) {
            $takeLogs = $takeLogs->whereExists(function ($query) use ($goods_title, $tableName) {
                $itemTableName = (new \app\admin\model\groupon\order\OrderItem())->getQuery()->getTable();

                $query = $query->table($itemTableName)->where($itemTableName . '.id=' . $tableName . 'order_item_id');

                if ($goods_title) {
                    $query = $query->where('goods_title', 'like', "%{$goods_title}%");
                }

                return $query;
            });
        }

        return $takeLogs;
    }
}
